package org.dromara.utils.service;


import com.alibaba.fastjson.JSONObject;
import com.trainingstation.starters.openapi.sdk.ImageUtils;
import com.trainingstation.starters.openapi.sdk.R;
import com.trainingstation.starters.openapi.sdk.TSSDKService;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.device.domain.bo.SendToServer;
import org.dromara.utils.Utils;
import org.dromara.utils.domain.FaceDeleteJson;
import org.dromara.utils.domain.FaceJson;
import org.dromara.utils.domain.JsonResponse;
import org.dromara.utils.domain.Remark;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestTemplate;

import java.io.File;

/**
 * @author vito
 * @version 1.0
 */
@Slf4j
@Service
public class SynchronizeImageService {
    @Autowired
    private TSSDKService sdkService;
    private final RestTemplate restTemplate;

    @Autowired
    public SynchronizeImageService(RestTemplateBuilder restTemplateBuilder) {
        this.restTemplate = restTemplateBuilder.build();
    }

    public String checkImage(R ret){
        return switch (ret.getCode()) {
            case 0 -> "人脸照片检测成功，可以用于入库";
            case 1 -> "图片过大，文件或分辨率已经超过 4M";
            case 2 -> "人脸轮廓不清晰，或大于 1 个人脸";
            case 3 -> "非活体，可能是手机翻拍的其他照片";
            case 4 -> "严格定义人脸不清晰";
            case 5 -> "人脸像素高度不够 500";
            case 6 -> "人脸占图片比例不合规";
            case 7 -> "图片导致";
            case 8 -> "图片中不能戴墨镜、口罩等遮挡物";
            case 9 -> "人脸面部模糊，细节体现不足";
            case 10 -> "图片采集质量太低，尝试重新拍照";
            default -> "未知错误代码：" + ret.getCode();
        };
    }
    private String tryRotateImage(File faceImage) {
        try {
            int[] wh = sdkService.getWidthOrHeight(faceImage);
            ImageUtils.rotate(faceImage.getAbsolutePath(), faceImage.getAbsolutePath(), 0, wh[1], wh[0]);
            return "已经自动矫正图片：" + faceImage.getName();
        } catch (Exception e) {
            return "图片旋转失败：" + e.getMessage();
        }
    }

    public JsonResponse sendImageIntoDevice(File file,String stuNum,String url,String studentName) {
        // 休眠1秒，防止图片还未写入磁盘
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            // 记录中断的异常日志
            log.error("线程中断异常", e);
        }
        String base64 = Utils.toBase64(file);
        FaceJson faceJson=new FaceJson();
        faceJson.setUface(base64);
        faceJson.setUid(stuNum);
        if (StringUtils.isNotEmpty(studentName)) {
            Remark remark=new Remark();
            remark.setName(studentName);
            faceJson.setRemark(remark);
        }
        String respon = this.sendPostRequest(url,faceJson);
        return this.doResponse(respon);
    }
    public JsonResponse removeImageFromDevice(String stuNum,String url) {
        FaceDeleteJson faceJson=new FaceDeleteJson();
        faceJson.setUid(stuNum);
        faceJson.setForceDelete(true);
        String respon = this.sendPostRequest(url,faceJson);

       return this.doResponse(respon);
    }

    private JsonResponse doResponse(String respon){
        JsonResponse entity =new JsonResponse();
        if(!"1".equals(respon)){
            try{
                JSONObject jsonObject = JSONObject.parseObject(respon);
                Long code = jsonObject.getLongValue("code");
                String message = jsonObject.getString("message");
                entity.setCode(code);
                entity.setMessage(message);
            } catch (Exception e) {
                entity.setCode(500L);
                entity.setMessage("Json转化错误");
            }
        }else if("1".equals(respon)){
            entity.setCode(41L);
            entity.setMessage("设备不在线，请检查设备");
        }else {
            entity.setCode(42L);
            entity.setMessage("请求超时，请重试");
        }
        return entity;
    }
    public String sendPostRequest(String url, Object requestBody) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Object> entity = new HttpEntity<>(requestBody, headers);
        int i=0;
        while (i<2) {
            try {
                // 发起请求
                ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class,20000);
                return response.getBody();
            } catch (ResourceAccessException e) {
                // 捕获超时异常并重新请求
                if (e.getCause() instanceof java.net.SocketTimeoutException || e.getCause() instanceof java.util.concurrent.TimeoutException) {
                    log.info("请求超时，正在重试...", e);
                    String s = url.substring(0, url.indexOf("api")) + "/api/v1/ops/version";
                    HttpEntity<Object> entity1 = new HttpEntity<>(headers);
                    SendToServer sendToServer=new SendToServer();
                    sendToServer.setMethod("GET");
                    sendToServer.setUrl(s);
                    String s1 =this.sendRequest(entity1,sendToServer);
                    if("1".equals(s1)){
                        return "1";
                    }
                    if(i>1){
                        return "2";
                    }
                    i++;
                    // 重新发起请求
                    continue;
                }else if(e.getCause() instanceof java.io.IOError){
                    return "1";
                }
                throw e;
            } catch (Exception e) {
                // 捕获其他异常并抛出
                throw new RuntimeException("请求失败，无法处理异常", e);
            }
        }
        return "1";
    }

    public String sendGetOrPostRequest(SendToServer sendToServer) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        if(StringUtils.isNotEmpty(sendToServer.getToken())&&StringUtils.isNotEmpty(sendToServer.getUserId())){
            headers.set("UserID",sendToServer.getUserId());
            headers.set("Token",sendToServer.getToken());
        }
        if(StringUtils.isNotEmpty(sendToServer.getAuthorization())){
            headers.set("Authorization",sendToServer.getAuthorization());
        }
        HttpEntity<Object> entity ="GET".equals(sendToServer.getMethod())? new HttpEntity<>(headers): new HttpEntity<>(sendToServer.getRequestBody(), headers);
        return this.sendRequest(entity,sendToServer);
    }
    public String sendRequest(HttpEntity<Object> entity,SendToServer sendToServer) {
        try {
            // 发起请求
            ResponseEntity<String> response = restTemplate.exchange(sendToServer.getUrl(), "GET".equals(sendToServer.getMethod())?HttpMethod.GET:HttpMethod.POST, entity, String.class);
            return response.getBody();
        } catch (ResourceAccessException e) {
            // 捕获超时异常并重新请求
            if (e.getCause() instanceof java.net.SocketTimeoutException || e.getCause() instanceof java.util.concurrent.TimeoutException||e.getCause() instanceof java.io.IOError) {
                return "1";
            }
            throw e;
        } catch (Exception e) {
            // 捕获其他异常并抛出
            throw new RuntimeException("请求失败，无法处理异常", e);
        }
    }
    public byte[] getImage(SendToServer sendToServer) {
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36");
            HttpEntity<Object> entity =new HttpEntity<>(headers);
            // 发起请求
            ResponseEntity<byte[]> response = restTemplate.exchange(sendToServer.getUrl(), "GET".equals(sendToServer.getMethod())?HttpMethod.GET:HttpMethod.POST, entity, byte[].class);
            return response.getBody();
        }  catch (Exception e) {
            // 捕获其他异常并抛出
            throw new RuntimeException("请求失败，无法处理异常", e);
        }
    }



}
